{% extends 'base.html' %}
{% load static %}

{% block title %}我的活动 - 本地有约{% endblock %}

{% block content %}
<div class="page-header">
    <div class="container">
        <h1><i class="fas fa-list"></i> 我的活动</h1>
        <p>管理您创建和参与的活动</p>
    </div>
</div>

<div class="container mb-5">
    <!-- 标签页导航 -->
    <ul class="nav nav-tabs mb-4" id="myActivityTabs" role="tablist">
        <li class="nav-item" role="presentation">
            <button class="nav-link active" id="created-tab" data-bs-toggle="tab" data-bs-target="#created" type="button">
                <i class="fas fa-plus-circle"></i> 我创建的 (<span id="createdCount">0</span>)
            </button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" id="joined-tab" data-bs-toggle="tab" data-bs-target="#joined" type="button">
                <i class="fas fa-calendar-check"></i> 我参与的 (<span id="joinedCount">0</span>)
            </button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" id="history-tab" data-bs-toggle="tab" data-bs-target="#history" type="button">
                <i class="fas fa-history"></i> 历史记录
            </button>
        </li>
    </ul>
    
    <!-- 标签页内容 -->
    <div class="tab-content" id="myActivityTabContent">
        <!-- 我创建的 -->
        <div class="tab-pane fade show active" id="created" role="tabpanel">
            <div class="mb-3">
                <a href="{% url 'activities:create' %}" class="btn btn-gradient-primary">
                    <i class="fas fa-plus"></i> 创建新活动
                </a>
            </div>
            <div id="createdActivities">
                <div class="text-center py-5">
                    <div class="loader"></div>
                </div>
            </div>
        </div>
        
        <!-- 我参与的 -->
        <div class="tab-pane fade" id="joined" role="tabpanel">
            <div id="joinedActivities">
                <div class="text-center py-5">
                    <div class="loader"></div>
                </div>
            </div>
        </div>
        
        <!-- 历史记录 -->
        <div class="tab-pane fade" id="history" role="tabpanel">
            <div id="historyActivities">
                <div class="text-center py-5">
                    <div class="loader"></div>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
    // 加载我创建的活动
    function loadCreatedActivities() {
        axios.get('/api/activities/?creator={{ user.id }}')
            .then(response => {
                const activities = response.data.results || response.data;
                const container = document.getElementById('createdActivities');
                document.getElementById('createdCount').textContent = activities.length;
                
                if (activities.length === 0) {
                    container.innerHTML = `
                        <div class="empty-state">
                            <i class="fas fa-calendar-plus"></i>
                            <h3>还没有创建任何活动</h3>
                            <p>创建您的第一个活动，邀请朋友参加</p>
                            <a href="{% url 'activities:create' %}" class="btn btn-gradient-primary">
                                <i class="fas fa-plus"></i> 创建活动
                            </a>
                        </div>
                    `;
                } else {
                    container.innerHTML = activities.map(activity => renderActivityCard(activity, true)).join('');
                }
            })
            .catch(error => {
                console.error('加载失败:', error);
            });
    }
    
    // 加载我参与的活动
    function loadJoinedActivities() {
        axios.get('/api/activities/?participant={{ user.id }}')
            .then(response => {
                const activities = response.data.results || response.data;
                const container = document.getElementById('joinedActivities');
                document.getElementById('joinedCount').textContent = activities.length;
                
                if (activities.length === 0) {
                    container.innerHTML = `
                        <div class="empty-state">
                            <i class="fas fa-calendar-times"></i>
                            <h3>还没有参与任何活动</h3>
                            <p>去发现有趣的活动吧</p>
                            <a href="{% url 'activities:list' %}" class="btn btn-gradient-primary">
                                <i class="fas fa-search"></i> 浏览活动
                            </a>
                        </div>
                    `;
                } else {
                    container.innerHTML = activities.map(activity => renderActivityCard(activity, false)).join('');
                }
            })
            .catch(error => {
                console.error('加载失败:', error);
            });
    }
    
    // 加载历史活动
    function loadHistoryActivities() {
        axios.get('/api/activities/?status=completed&participant={{ user.id }}')
            .then(response => {
                const activities = response.data.results || response.data;
                const container = document.getElementById('historyActivities');
                
                if (activities.length === 0) {
                    container.innerHTML = `
                        <div class="empty-state">
                            <i class="fas fa-history"></i>
                            <h3>暂无历史记录</h3>
                        </div>
                    `;
                } else {
                    container.innerHTML = activities.map(activity => renderActivityCard(activity, false)).join('');
                }
            })
            .catch(error => {
                console.error('加载失败:', error);
            });
    }
    
    // 渲染活动卡片
    function renderActivityCard(activity, isCreator) {
        const statusBadge = getStatusBadge(activity.status);
        
        return `
            <div class="card card-custom mb-3">
                <div class="row g-0">
                    <div class="col-md-3">
                        <img src="${activity.cover_image || '/static/img/default-activity.jpg'}" 
                             class="img-fluid h-100" 
                             style="object-fit: cover;" 
                             alt="${activity.title}">
                    </div>
                    <div class="col-md-9">
                        <div class="card-body">
                            <div class="d-flex justify-content-between align-items-start mb-2">
                                <h5 class="card-title">
                                    <a href="/activities/${activity.id}/" class="text-decoration-none">${activity.title}</a>
                                </h5>
                                <span class="badge ${statusBadge.class}">${statusBadge.text}</span>
                            </div>
                            <p class="card-text text-muted mb-3">${activity.description.substring(0, 100)}...</p>
                            <div class="row g-2 mb-3">
                                <div class="col-md-6">
                                    <small class="text-muted">
                                        <i class="fas fa-calendar"></i> ${formatDate(activity.start_time)}
                                    </small>
                                </div>
                                <div class="col-md-6">
                                    <small class="text-muted">
                                        <i class="fas fa-users"></i> ${activity.current_participants}/${activity.max_participants}
                                    </small>
                                </div>
                            </div>
                            <div class="d-flex gap-2">
                                <a href="/activities/${activity.id}/" class="btn btn-sm btn-outline-primary">
                                    <i class="fas fa-eye"></i> 查看
                                </a>
                                ${isCreator ? `
                                    <a href="/activities/${activity.id}/edit/" class="btn btn-sm btn-outline-secondary">
                                        <i class="fas fa-edit"></i> 编辑
                                    </a>
                                    <button class="btn btn-sm btn-outline-danger" onclick="deleteActivity(${activity.id})">
                                        <i class="fas fa-trash"></i> 删除
                                    </button>
                                ` : ''}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }
    
    // 获取状态徽章
    function getStatusBadge(status) {
        const badges = {
            'draft': { text: '草稿', class: 'bg-secondary' },
            'published': { text: '已发布', class: 'bg-success' },
            'ongoing': { text: '进行中', class: 'bg-primary' },
            'completed': { text: '已结束', class: 'bg-secondary' },
            'cancelled': { text: '已取消', class: 'bg-danger' },
        };
        return badges[status] || { text: '未知', class: 'bg-secondary' };
    }
    
    // 删除活动
    function deleteActivity(activityId) {
        if (!confirm('确定要删除这个活动吗？')) return;
        
        axios.delete(`/api/activities/${activityId}/`)
            .then(response => {
                showSuccess('删除成功');
                loadCreatedActivities();
            })
            .catch(error => {
                showError('删除失败');
            });
    }
    
    // 标签页切换事件
    document.getElementById('created-tab').addEventListener('shown.bs.tab', loadCreatedActivities);
    document.getElementById('joined-tab').addEventListener('shown.bs.tab', loadJoinedActivities);
    document.getElementById('history-tab').addEventListener('shown.bs.tab', loadHistoryActivities);
    
    // 页面加载时加载数据
    document.addEventListener('DOMContentLoaded', function() {
        loadCreatedActivities();
    });
</script>
{% endblock %}
